package com.bsj.power.sdk.config.hksdk.video;

import com.bsj.power.common.util.DateUtils;
import com.bsj.power.sdk.config.hksdk.HCNetSDK;
import com.bsj.power.sdk.util.VideoConvertUtil;
import com.sun.jna.ptr.IntByReference;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static com.bsj.power.sdk.config.hksdk.HKSDKClientManage.hCNetSDK;

/**
 * @author yinhao
 * @version 1.0
 * @description 使用海康SDK操作CVR
 * @date 2024/8/23
 */
@Slf4j
public class VideoOperate {

    /**
     * 使用海康SDK进行文件下载(原始文件为h.264)并转码(转码为MP4给前端显示)
     *
     * @param userID    cvr 登录ID
     * @param channel   对应设备实际通道号
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param inputPath 输出文件地址
     */
    public static void downloadRecordByTime(int userID, Integer channel,
                                            String startTime, String endTime,
                                            String inputPath) {
        HCNetSDK.NET_DVR_PLAYCOND net_dvr_playcond = new HCNetSDK.NET_DVR_PLAYCOND();
        net_dvr_playcond.read();
        //通道号 NVR设备路数小于32路的起始通道号从33开始，依次增加
        net_dvr_playcond.dwChannel = channel;
        Date start = DateUtils.strToDate(startTime);
        Date end = DateUtils.strToDate(endTime);
        //加两分钟
//        Date startDate = new Date(start.getTime());
//        Date endDate = new Date(end.getTime());
        //开始时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        net_dvr_playcond.struStartTime.dwYear = calendar.get(Calendar.YEAR);
        net_dvr_playcond.struStartTime.dwMonth = calendar.get(Calendar.MONTH) + 1;
        net_dvr_playcond.struStartTime.dwDay = calendar.get(Calendar.DAY_OF_MONTH);
        net_dvr_playcond.struStartTime.dwHour = calendar.get(Calendar.HOUR_OF_DAY);
        net_dvr_playcond.struStartTime.dwMinute = calendar.get(Calendar.MINUTE);
        net_dvr_playcond.struStartTime.dwSecond = calendar.get(Calendar.SECOND);
        //停止时间
        calendar.setTime(end);
        net_dvr_playcond.struStopTime.dwYear = calendar.get(Calendar.YEAR);
        net_dvr_playcond.struStopTime.dwMonth = calendar.get(Calendar.MONTH) + 1;
        net_dvr_playcond.struStopTime.dwDay = calendar.get(Calendar.DAY_OF_MONTH);
        net_dvr_playcond.struStopTime.dwHour = calendar.get(Calendar.HOUR_OF_DAY);
        net_dvr_playcond.struStopTime.dwMinute = calendar.get(Calendar.MINUTE);
        net_dvr_playcond.struStopTime.dwSecond = calendar.get(Calendar.SECOND);
        net_dvr_playcond.write();
        ScheduledExecutorService downloadtimer;
        int m_lLoadHandle;
        //下载的内容源文件为h264, 需要下载下来后将h264文件转换为mp4
        String sFileName = inputPath.replaceAll("mp4", "h264");
        String directoryPath = sFileName.substring(0, sFileName.length() - 23);
        File directory = new File(directoryPath);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        log.info("回放下载原始文件路径: {}", sFileName);
        m_lLoadHandle = hCNetSDK.NET_DVR_GetFileByTime_V40(userID, sFileName, net_dvr_playcond);
        if (m_lLoadHandle >= 0) {
            hCNetSDK.NET_DVR_PlayBackControl(m_lLoadHandle, HCNetSDK.NET_DVR_PLAYSTART, 0, null);
            Date nowTime = new Date(System.currentTimeMillis());
            SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
            log.info("开始下载时间： {}", sdFormatter.format(nowTime));
            //新建定时器
            downloadtimer = new ScheduledThreadPoolExecutor(1);
            //0秒后开始响应函数
            downloadtimer.scheduleWithFixedDelay(() -> {
                downloadTask(m_lLoadHandle, downloadtimer, sFileName, inputPath);
            }, 10, 30, TimeUnit.SECONDS);
        } else {
            log.error("按时间下载失败 :{}", hCNetSDK.NET_DVR_GetLastError());
            return;
        }
    }

    /*************************************************
     类:      DownloadTask
     类描述:  下载定时器响应函数
     *************************************************/
//    static class DownloadTask extends java.util.TimerTask  {
//        private int m_lLoadHandle;
//        private ScheduledExecutorService downloadtimer;
//        private String sFileName;
//        private String outputFile;
//        public DownloadTask(int m_lLoadHandle, ScheduledExecutorService downloadtimer,
//                            String sFileName, String outputFile){
//            this.m_lLoadHandle = m_lLoadHandle;
//            this.downloadtimer = downloadtimer;
//            this.sFileName = sFileName;
//            this.outputFile = outputFile;
//        }
//        @Override
//        public void run() {
//            IntByReference nPos = new IntByReference(0);
//            hCNetSDK.NET_DVR_PlayBackControl(m_lLoadHandle, HCNetSDK.NET_DVR_PLAYGETPOS, 0, nPos);
//            if (nPos.getValue() > 100) {
//                m_lLoadHandle = -1;
//                downloadtimer.shutdown();
//                log.warn("由于网络原因或DVR忙,下载异常终止!");
//            }
//            if (nPos.getValue() == 100) {
//                Date nowTime = new Date(System.currentTimeMillis());
//                SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
//                log.info("结束下载时间： {}", sdFormatter.format(nowTime));
//                m_lLoadHandle = -1;
//                downloadtimer.shutdown();
//                log.info("按时间下载结束!");
//                try {
//                    VideoConvertUtil.convert(sFileName, outputFile);
//                } catch (Exception e) {
//                    log.error("文件转换失败，原文件: {}, 待转换文件地址: {}", sFileName, outputFile);
//                    e.printStackTrace();
//                }
//            }
//        }
//    }
    private static void downloadTask(int m_lLoadHandle, ScheduledExecutorService downloadtimer,
                                     String sFileName, String outputFile) {

        IntByReference nPos = new IntByReference(0);
        hCNetSDK.NET_DVR_PlayBackControl(m_lLoadHandle, HCNetSDK.NET_DVR_PLAYGETPOS, 0, nPos);
        if (nPos.getValue() > 100) {
            m_lLoadHandle = -1;
            downloadtimer.shutdown();
            log.warn("由于网络原因或DVR忙,下载异常终止!");
        }
        if (nPos.getValue() == 100) {
            Date nowTime = new Date(System.currentTimeMillis());
            SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
            log.info("结束下载时间： {}", sdFormatter.format(nowTime));
            m_lLoadHandle = -1;
            downloadtimer.shutdown();
            log.info("按时间下载结束!");
            try {
                VideoConvertUtil.convert(sFileName, outputFile);
            } catch (Exception e) {
                log.error("文件转换失败，原文件: {}, 待转换文件地址: {}", sFileName, outputFile);
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        String s = "/soft/file/ALARM-UWB/20240824/90/20240824225022796.h264";
        String substring = s.substring(0, s.length() - 23);
        System.out.println(substring);
    }
}
